package morphage.gui;

import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.awt.Toolkit;

/**
 * Used to load resources such as image files.
 * 
 * @author jis
 * 
 */
public class ResourceManager
{
  private static Toolkit toolkit = null;
  private static HashMap<String, Image> images = new HashMap<String, Image>();

  private static Toolkit getToolkit()
  {
    if (toolkit == null)
      toolkit = Toolkit.getDefaultToolkit();
    return toolkit;
  }

  /**
   * If the file is not found on the file system, the file will be searched in a
   * current jar archive if the app is ran from there.
   * 
   * @param path
   *          path of an image file
   * @return
   */
  public static Image getImage(String path) throws FileNotFoundException,
      Exception
  {
    Image image = images.get(path);
    if (image == null)
    {
      try
      {
        // Load image
        if (new File(path).exists())
          image = getToolkit().getImage(path);
        else
          image = getToolkit().getImage(ClassLoader.getSystemResource(path));

      } catch (java.lang.NullPointerException ex)
      {
        throw new Exception(ex);
      }
      // Keep the image
      if (image != null)
        images.put(path, image);
      else
        throw new FileNotFoundException(path);
    }

    return image;
  }
}
